(() => {
	window.popupGroupAddBox = function (id) {
		if(!Core.isNumber(id)) {
			id = $(id).data('blockId');
		}
		
		if(PageHelper.getCurrentViewPage()) {
			let currentViewPage = PageHelper.getCurrentViewPage();
			let m = new BlockModel;
			
			if(id) {
				m.load(id);
			}
			
			layui.layer.open({
				type:1,
				btn:['确定'],
				content:Core.renderSrcFile('page/home/tools/add-group-block.html', m),
				title:'添加组',
				yes: function (index) {
					let id = $('#add_group_block_id').val();
					let label = $('#add_group_block_label').val();

					if(label == '') {
						CoreHelper.alertError('组名不能为空');
						return false;
					}
					
					let blockModel = new BlockModel();
					
					if(id) {
						blockModel.load(id);
						
						if(!blockModel.getId()) {
							CoreHelper.alertError(`保存失败, 记录不存在`);
							layui.layer.close(index);
							return true;
						}
					}
					
					blockModel.setPageId(currentViewPage).setLabel(label).setType(BlockModel.TYPE.GROUP).save();
					
					if(!blockModel.ok()) {
						CoreHelper.alertError(`保存失败: ${blockModel.getError()}`);
						return false;
					}

					if(id) {
						BlockHelper.setFrontendTitle(id, label);
					} else {
						let html = BlockHelper.render(blockModel);
						CoreHelper.PageContentElement.append($(html));
					}
					
					layui.layer.close(index);
					return true;
				}
			});
			
			$('#add_group_block_label').focus();
		}
	};
})();
